package com.jiaai.cloud.file.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jiaai.cloud.base.entity.RestResultGenerator;
import com.jiaai.cloud.base.exception.ServiceException;
import com.jiaai.cloud.base.util.UploadUtil;
import com.jiaai.cloud.file.entity.TFile;
import com.jiaai.cloud.file.service.ITFileService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * <p>
 * 文件信息表 前端控制器
 * </p>
 *
 * @author 佳爱网络科技
 * @since 2017-10-10
 */
@Controller
@RequestMapping("/api/v1/comm/tfile")
public class TFileController {

    @Autowired
    private ITFileService itFileService;

    private static final Logger LOGGER = LoggerFactory.getLogger(TFileController.class);

    /**
     * 上传文件, 多个
     *  ,返回URL地址
     * @param directories
     * @param request
     * @param customerId
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/upload/{directories}/{cid}", method = RequestMethod.POST)
    @ResponseBody
    public Object upload(@PathVariable(value = "directories",required = false)String  directories
            , HttpServletRequest request
            , @PathVariable("cid")Integer customerId
    ) throws UnsupportedEncodingException, ServiceException {
        Date date = new Date();
        List<TFile> list = new ArrayList<>();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        Map<String, String> urls=new HashMap<>();
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                String key=iter.next();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(key);
                String fileName= UploadUtil.copyFile(file,directories);
                // String url=URLEncoder.encode(UploadUtil.getHttpUrl(fileName,directories),"utf-8");
                String url = UploadUtil.getHttpUrl(fileName,directories);
                urls.put(file.getOriginalFilename(), url);
                list.add(new TFile(fileName, file.getOriginalFilename(), date, url, customerId));
            }
        }
        itFileService.insertBatch(list);
        LOGGER.info(urls.toString());
        try {
            return RestResultGenerator.genSuccessResult(urls);
        } catch (Exception e){
            throw new ServiceException("上传失败" ,e.getMessage());
        }
    }

    /**
     * 下载文件
     * @param request
     * @param response
     * @param fname 文件名称
     * @param director 对应的server硬盘路径
     */
    @RequestMapping(value = "/dwnload/{director}", method = RequestMethod.GET, produces = "application/octet-stream; charset=utf-8")
    public void downFile(HttpServletRequest request, HttpServletResponse response
            , String fname
            , @PathVariable("director") String director){
        String fullPath= UploadUtil.getFilePath(fname,director);
        File downloadFile = new File(fullPath);
        ServletContext context = request.getServletContext();
        // get MIME type of the file
        String mimeType = context.getMimeType(fullPath);
        LOGGER.info("file type: " + mimeType);
        mimeType = "application/octet-stream; charset=utf-8";

        // set content attributes for the response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());
        // set headers for the response

        Wrapper<TFile> ew = new EntityWrapper<>();
        ew.eq("file_id", downloadFile.getName())
                .setSqlSelect("old_name");
        String oldName = (String) itFileService.selectObj(ew);

        String headerKey = "Content-Disposition";
        String headerValue = null;

        try {
            headerValue = "attachment; filename=".concat(new String(oldName.getBytes(), "ISO-8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        response.setHeader(headerKey, headerValue);
        // Copy the stream to the response's output stream.
        try {
            InputStream myStream = new FileInputStream(fullPath);
            IOUtils.copy(myStream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *删除文件
     * @param directories
     * @param fileId
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/delete/{directories}/{fileId}", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Object addAOutApply(@PathVariable("directories")String directories
            , @PathVariable("fileId")String fileId) throws ServiceException {
        try {
            String fullPath= UploadUtil.getFilePath(fileId,directories);
            File targetFile = new File(fullPath);

            if (targetFile.exists() && targetFile.isFile()) {
                if (targetFile.delete()) {
                    LOGGER.info("删除单个文件" + fileId + "成功！");
                } else {
                    LOGGER.info("删除单个文件" + fileId + "失败！");
                    throw new Exception("\"删除单个文件\" + fileId + \"失败！\"");
                }
            } else {
                LOGGER.info("删除单个文件失败：" + fileId + "不存在！");
                throw new Exception("删除单个文件失败：" + fileId + "不存在！");
            }

            itFileService.deleteById(fileId);
            return RestResultGenerator.genSuccessResult("删除成功");
        } catch (Exception e){
            throw new ServiceException("删除失败", e.getMessage());
        }
    }

}
